package top.yudoge.dogeeditorserverj.db.mysql;

import top.yudoge.dogeeditorserverj.db.*;
import top.yudoge.dogeeditorserverj.db.config.SQLDataSource;
import top.yudoge.dogeeditorserverj.db.exceptions.BootStrapError;

import java.sql.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MySQLDataSourceConnector extends AbstractSQLDataSourceConnector {

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new BootStrapError("Can't find MySQL Driver");
        }
    }

    private final SQLDataSource dataSource;

    private Connection connection;

    public MySQLDataSourceConnector(SQLDataSource sqlDataSource) {
        this.dataSource = sqlDataSource;
        try {
            prepareConnection();
        } catch (SQLException e) {
            throw new BootStrapError("Cannot connect to MySQL Datasource. target => " + sqlDataSource);
        }
    }

    private void prepareConnection() throws SQLException {
        this.connection = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
    }

    @Override
    protected Connection getConnection() throws SQLException {
        if (connection.isClosed()) {
            prepareConnection();
        }
        return connection;
    }

    @Override
    public List<Schema> getSchemas(String dbName) {
        Schema schema = new Schema();
        schema.setName("%");
        return Arrays.asList(schema);
    }

    @Override
    public SQLDataSource getDataSource() {
        return dataSource;
    }
}
